package com.macaku.controller;

import com.macaku.common.SystemJsonResponse;
import com.macaku.domain.po.ShortLink;
import com.macaku.service.ShortLinkService;
import com.macaku.util.HttpUrlValidator;
import com.macaku.util.RedisCache;
import com.macaku.util.ShortLinkUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Date;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2024-01-12
 * Time: 20:14
 */
@RestController
@Api(tags = "短链接测试接口")
@Slf4j
@RequestMapping("/shortlink")
@RequiredArgsConstructor
public class ShortLinkController {

    @Value("${redirect.domain}")
    private String domain;
    @Value("${server.port}")
    private String port;

    private final ShortLinkService shortLinkService;

    private final RedisCache redisCache;

    @GetMapping("/{code}")
    @ApiOperation("短链接重定向到长链接")
    public RedirectView getShortLink(@PathVariable("code") @ApiParam("短链接code") String code) {
        String originUrl = shortLinkService.getOriginUrl(code);
        return new RedirectView(originUrl);
    }

    @PostMapping("/trans")
    @ApiOperation("长链接转化短链接")
    public SystemJsonResponse transferAndSaveShortLink(@RequestParam("url") @ApiParam("原链接") String url) {
        //验证url
        if(!HttpUrlValidator.isHttpUrl(url) || !HttpUrlValidator.isUrlAccessible(url)) {
            throw new IllegalArgumentException("url is not valid");
        }
        String baseUrl = domain + ":" + port + "/shortlink/";
        String shortLinkURL = shortLinkService.transShortLinkURL(baseUrl, url);
        return SystemJsonResponse.SYSTEM_SUCCESS(shortLinkURL);
    }


}
